import { DIFM_FLOW, DIFM_FLOW_STORE } from '@automattic/onboarding';
import { useEffect } from 'react';
import difmImage from 'calypso/assets/images/difm/difm.svg';
import { triggerGuidesForStep } from 'calypso/lib/guides/trigger-guides-for-step';
import DIFMLanding from 'calypso/my-sites/marketing/do-it-for-me/difm-landing';
import useBranchSteps from 'calypso/signup/hooks/use-branch-steps';
import StepWrapper from 'calypso/signup/step-wrapper';
import { useDispatch } from 'calypso/state';
import { removeSiteSlugDependency } from 'calypso/state/signup/actions';
import { saveSignupStep, submitSignupStep } from 'calypso/state/signup/progress/actions';
import type { ChoiceType } from './types';

import './style.scss';

interface Props {
	goToNextStep: () => void;
	submitSignupStep: ( { stepName, wasSkipped }: { stepName: string; wasSkipped: boolean } ) => void;
	goToStep: ( stepName: string ) => void;
	flowName: string;
	stepName: string;
	existingSiteCount: number;
	signupDependencies: {
		back_to?: string;
		newOrExistingSiteChoice?: ChoiceType;
	};
}

export default function NewOrExistingSiteStep( props: Props ) {
	const dispatch = useDispatch();

	const { stepName, goToNextStep, existingSiteCount, flowName, signupDependencies } = props;
	const { back_to: backUrl } = signupDependencies;

	useEffect( () => {
		dispatch( saveSignupStep( { stepName } ) );
		triggerGuidesForStep( flowName, stepName );
	}, [ dispatch, flowName, stepName ] );

	// Show one button only for DIFM_FLOW and DIFM_FLOW_STORE, two buttons for all other flows
	const showTwoButtons = ! [ DIFM_FLOW, DIFM_FLOW_STORE ].includes( flowName );

	const branchSteps = useBranchSteps( stepName, () => [ 'difm-site-picker' ] );

	const handleSiteChoice = ( value: ChoiceType ) => {
		// Skip site picker when:
		// 1. In DIFM flow with no existing sites, or
		// 2. In other flows when explicitly choosing new site
		if (
			( ! showTwoButtons && existingSiteCount === 0 ) ||
			( showTwoButtons && value === 'new-site' )
		) {
			branchSteps( {} );
			dispatch( removeSiteSlugDependency() );
		}

		dispatch(
			submitSignupStep(
				{ stepName: stepName },
				{
					newOrExistingSiteChoice: value,
					forceAutoGeneratedBlogName: true,
				}
			)
		);
		goToNextStep();
	};

	const getPrimarySiteChoice = () => {
		if ( showTwoButtons ) {
			return 'new-site';
		}
		return existingSiteCount > 0 ? 'existing-site' : 'new-site';
	};

	return (
		<StepWrapper
			stepContent={
				<DIFMLanding
					onPrimarySubmit={ () => handleSiteChoice( getPrimarySiteChoice() ) }
					onSecondarySubmit={ () => handleSiteChoice( 'existing-site' ) }
					showNewOrExistingSiteChoice={ showTwoButtons }
					isStoreFlow={ 'do-it-for-me-store' === flowName }
				/>
			}
			hideFormattedHeader
			align="left"
			hideSkip
			backUrl={ backUrl }
			allowBackFirstStep={ !! backUrl }
			isHorizontalLayout={ false }
			isWideLayout
			headerImageUrl={ difmImage }
			{ ...props }
		/>
	);
}
